/*********************************************************************************
 *      Copyright:  (C) HuangXiangming
 *                  All rights reserved.
 *
 *       Filename:  ds_client.c
 *    Description:  This file is getting temperature function 
 *                 
 *        Version:  1.0.0(25/04/03)
 *         Author:  Huang Xiangming <huangxiangming@gmail.com>
 *      ChangeLog:  1, Release initial version on "25/04/03 15:35:43"
 *                 
 ********************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>

#include "get_data.h"

int get_temperature(float *temp)
{
	int             fd=-1;
	char            buf[128];   //一般给2的次方
	char            *ptr = NULL;
	DIR             *dirp = NULL;   //DIR结构体类似于FILE，是一个内部结构
	struct dirent   *direntp = NULL;    //dir结构体 
	char            w1_path[64]="/sys/bus/w1/devices/";
	char            chip_sn[32];
	int             found = 0;

	dirp = opendir(w1_path);      //打开目录
	if ( !dirp )
	{
		printf("open folder %s failure: %s\n", w1_path, strerror(errno));
		return -1;
	}

	
	while( (direntp=readdir(dirp)) != NULL)
	{
		if ( strstr(direntp->d_name, "28-") )    //在文件名中查找第一次出现字符串 28- 的位置，不包含终止符 '\0'
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn)); //把这个名字复制到chip_sn中
			found = 1;
		}
	}
	closedir(dirp);

    if ( !found )    //没找到 28- 开头文件的情况
	{
		printf("Can not find ds18b20 chipset\n");
		return -2;
	}
	
	strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));

	fd = open(w1_path,O_RDONLY);
	if ( fd < 0 )
	{
		printf("open file failure: %s\n",strerror(errno));
		return -3;
	}
	
	memset(buf, 0, sizeof(buf));    //字符串以\0结尾，\0是0，初始化
	if ( read(fd, buf, sizeof(buf)) < 0 )
	{
		printf("read data from fd=%d failure: %s\n", fd ,strerror(errno));
		return -4;
	}
	
	ptr=strstr(buf, "t=");      //寻找文件中 t= 的内容
	if ( !ptr )
	{
		printf("Can not find t= string\n");
		return -5;
	}

	ptr += 2;    //去掉“t=”，只留下温度值
	*temp = atof(ptr)/1000;     //ASCII转float

	close(fd);
	return 0;
}

int get_devid(char *id, int len, int sn)
{
	if( !id )
	{
		printf("Invalid input arugments\n");
		return -1;
	}

	memset(id, 0, len);
	snprintf(id, len, "rpi%04d", sn);
	return 0;
}


void get_time(char *sample_time, int time_len)
{
	time_t			now_time;
	int				rv;

	time(&now_time);
	rv=strftime(sample_time, time_len, "%Y%m%d %H:%M:%S", localtime(&now_time));
	return ;
}

void get_data(pack_t *data)
{
	get_temperature(&data->temp);
	get_time(data->sample_time, sizeof(data->sample_time)-1);
	//get_devid(data->id, data->len, data->sn);
}

void pack_data(pack_t *data, char *buf, int len)
{
	memset(buf, 0, len);
	snprintf(buf, len, "ID=%s\nTIME=%s\nTEMPERATURE=%.4f\n", data->id, data->sample_time, data->temp);
	
	return ;
}


